package edu.utdallas_elearn_calendar.utdallas_elearn_calendar_app;


import edu.utdallas_elearn_calendar.utdallas_elearn_calendar_app.UnivClassEvent;
import edu.utdallas_elearn_calendar.utdallas_elearn_calendar_db.CalDbAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
//import android.widget.Toast;

public class events extends Activity  implements OnClickListener {

	private static final int DELETE_ID = Menu.FIRST + 1;
	private Long mRowId;
	
	private CalDbAdapter dbHelper;
	public final static String FORMAT_DATE_TIME = "yyyy-MM-dd HH:mm";
	
	private Button toCalendar;
	private Button toClasses;
	private Button toSync;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.events);
        dbHelper = new CalDbAdapter(this);
		dbHelper.open();
		
		mRowId = null;
		Bundle extras = getIntent().getExtras();
		mRowId = (savedInstanceState == null) ? null : (Long) savedInstanceState
				.getSerializable(CalDbAdapter.ROW_ID);
		
		if (extras != null) {
			mRowId = extras.getLong(CalDbAdapter.ROW_ID);
		}
//		Toast.makeText(this, "The id number of this class record is " + mRowId + ".", Toast.LENGTH_LONG).show();
		showEvents();
		
		toCalendar = (Button) this.findViewById(R.id.toCalendar);
		toCalendar.setOnClickListener(this);
		
		toClasses = (Button) this.findViewById(R.id.toClasses);
		toClasses.setOnClickListener(this);
		
		toSync = (Button) this.findViewById(R.id.toSync);
		toSync.setOnClickListener(this);
    }
    
    public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v == toCalendar)
			viewCalendar();
		if(v == toClasses)
			viewClass();
		if(v == toSync)
			elearningSync();
	}    
    
	// Create the menu based on the XML defintion
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.event_menu, menu);  //add_event_menu
		return true;
	}
	
	// Reaction to the menu selection
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.view_class:
			viewClass();
			return true;
		case R.id.view_events:
			viewEvents();
			return true;
		case R.id.edit_event:
			editEvent();
			return true;
		case R.id.elearning_sync:
			elearningSync();
			return true;
		case R.id.view_event_type:
			viewEventType();
			return true;		
//		case R.id.view_priority:
//			viewPriority();
//			return true;
		case R.id.view_settings:
			viewPreferences();
			return true;
		case R.id.reset_database:
			dbHelper.reset();
			showEvents();
			return true;
		case R.id.set_demo_database:
			dbHelper.reset();
			dbHelper.addDummy();
			showEvents();
			return true;			
		}
		return super.onMenuItemSelected(featureId, item);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.view_class:
			viewClass();
			return true;
		case R.id.view_events:
			viewEvents();
			return true;
		case R.id.edit_event:
			editEvent();
			return true;
		case R.id.elearning_sync:
			elearningSync();
			return true;			
		case R.id.view_event_type:
			viewEventType();
			return true;		
//		case R.id.view_priority:
//			viewPriority();
//			return true;
		case R.id.view_settings:
			viewPreferences();
			return true;
		case R.id.reset_database:
			dbHelper.reset();
			showEvents();
			return true;
		case R.id.set_demo_database:
			dbHelper.reset();
			dbHelper.addDummy();
			showEvents();
			return true;			
		}
		return super.onOptionsItemSelected(item);
	}
	
    private void showEvents()
    {
    	String due_date = "";
    	String year = "";
    	String time = "";
    	
    	SimpleDateFormat df = new SimpleDateFormat();
		df.applyPattern(FORMAT_DATE_TIME);
		
    	// first clear all the events	
    	ViewGroup layout = (ViewGroup) this.findViewById(R.id.table_events01);
    	layout.removeAllViews();
    	
    	setLastSyncText();
    	
    	// now get the new events
    	ArrayList<UnivClassEvent> listEvents = new ArrayList<UnivClassEvent>();
        listEvents = GetEvents();
               
        for(UnivClassEvent univEvent : listEvents)
        {	        
        	Button b = new Button(this.getApplicationContext());
	        b.setTextSize(17);
	        b.setId((int)univEvent.EventId);
	        	        
			switch (univEvent.PriorityVal) {
			case 1:
				b.setTextColor(this.getResources().getColor(R.color.UTDRed));
				break;
			case 2:
				b.setTextColor(this.getResources().getColor(R.color.UTDBlue));
				break;
			case 3:
				b.setTextColor(this.getResources().getColor(R.color.UTDGreen));
				break;
			case 4:
				b.setTextColor(this.getResources().getColor(R.color.UTDBlack));
				break;
			}
	        
	        due_date = df.format(univEvent.DueDate);
	    	year = due_date.substring(0, due_date.indexOf("-"));
	    	time = due_date.substring(due_date.indexOf(" ")+1, due_date.length());
			due_date = due_date.substring(due_date.indexOf("-")+1, due_date.indexOf(" "));
			due_date = due_date + "-" + year + " " + time;
	        
	        b.setText(due_date + "\n" + univEvent.Name);
//	        b.setText(univEvent.DueDate + "\n" + univEvent.Name);
        	b.setTag(univEvent.EventId);        	
        	b.setOnClickListener(btnEventClick);
        	b.setOnCreateContextMenuListener(this);
	        layout.addView(b);
        }
    }
    
    private OnClickListener btnEventClick = new OnClickListener()
    {		
    	public void onClick(View v)
    	{
    		try
    		{	    	
        		Intent viewEvent = new Intent(v.getContext(), event_edit.class);
        		Button b = (Button) v;
        		long id = Long.parseLong(b.getTag().toString());
	    		Log.d("Events", "btnEventClick: passing id to screen: " + id);
	    		viewEvent.putExtra("_id", id);	    		
				startActivity(viewEvent);
				//startActivityForResult(viewEvent, EDIT_EVENT);
    		}
    		catch(Exception e)
    		{
    			Log.e("Events", "btnEventClick error: " + e.toString());
    		}
    	}
    };

	public ArrayList<UnivClassEvent> GetEvents()
	{
		Log.i("DATABASE", "call to GetEvents");
		ArrayList<UnivClassEvent> listEvents = new ArrayList<UnivClassEvent>();
		
		SimpleDateFormat df = new SimpleDateFormat();
		df.applyPattern(FORMAT_DATE_TIME);
		
		try
		{			
			Cursor result;
			
			if (mRowId != null) {
				result = dbHelper.getViewAllClassEvents(mRowId);
			} else {
				result = dbHelper.getViewAllEvents();
			}
			
			startManagingCursor(result);
			
			if(result.getCount() > 0)
			{
				result.moveToFirst();
				do
				{
					UnivClassEvent Event = new UnivClassEvent();
					Event.EventId = result.getLong(result.getColumnIndexOrThrow(CalDbAdapter.EVENT_ID));
					Event.ClassId = result.getLong(result.getColumnIndexOrThrow(CalDbAdapter.CLASS_ID));
					Event.EventTypeId = result.getLong(result.getColumnIndexOrThrow(CalDbAdapter.EVENT_TYPE_ID));
					Event.EventType = result.getString(result.getColumnIndexOrThrow(CalDbAdapter.EVENT_TYPE));
					Event.Name = result.getString(result.getColumnIndexOrThrow(CalDbAdapter.EVENT_NAME));
	
					String eDueDate = result.getString(result.getColumnIndexOrThrow(CalDbAdapter.EVENT_DUE));
					if(eDueDate != null)
						Event.DueDate = df.parse(eDueDate);					
					
					Event.RecurringType = result.getInt(result.getColumnIndexOrThrow(CalDbAdapter.EVENT_RECURRENCE));
					Event.ReminderId = result.getLong(result.getColumnIndexOrThrow(CalDbAdapter.REMINDER_ID));
					Event.MinutesPrior = result.getLong(result.getColumnIndexOrThrow(CalDbAdapter.REMINDER_MINUTES));
					Event.PriorityId = result.getLong(result.getColumnIndexOrThrow(CalDbAdapter.EVENT_PRIORITY));
					Event.PriorityVal = result.getInt(result.getColumnIndexOrThrow(CalDbAdapter.PRIORITY_VAL));
					Event.Color = result.getString(result.getColumnIndexOrThrow(CalDbAdapter.PRIORITY_COLOR));
					
					listEvents.add(Event);
				}
				while(result.moveToNext());
			}
			else
			{
				Log.i("DATABASE", "GetEvents: no events found");
			}
			result.close();
		}
		catch(Exception e)
		{
			Log.e("DATABASE", "GetEvents error: " + e.toString() + e.getMessage());
		}
		return listEvents;
	}        
	
	private void editEvent() {
		Intent i = new Intent(this, event_edit.class);
		//startActivityForResult(i, EDIT_EVENT);
		startActivity(i);
	}
    
    /**
     * onActivityResult is called once the startActivityForResult
     * activity returns
     */
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		showEvents();
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);

		menu.setHeaderTitle(R.string.event_delete);
		
		// v.getId() was set by the button and is actually the row_id
		menu.add(v.getId(), DELETE_ID, 0, R.string.menu_delete);
		menu.add(0, DELETE_ID+1, 0, R.string.menu_cancel);
	}
	
	/**
	 * This method determines which button/class was selected
	 * this method cheats the MenuItem a little, instead of 
	 * using the GroupId to identify which group the menu 
	 * item is in we use it to store the row_id of the 
	 * event selected
	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {
//		Toast.makeText(this, "The id number of this class record is " + item.getGroupId() + ".", Toast.LENGTH_LONG).show();
		
		switch (item.getItemId()) {
		case DELETE_ID:
			dbHelper.deleteReminder(item.getGroupId());
			dbHelper.deleteEvent(item.getGroupId());
			showEvents();
			return true;
		case DELETE_ID+1:
			return false;
		}

		return super.onContextItemSelected(item);
	}	

	@Override
    public void onPause() {
    	super.onPause();
//    	dbHelper.close();
    }
    
	@Override
	protected void onResume() {
		super.onResume();
//		dbHelper.open();
		showEvents();
	}	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (dbHelper != null) {
			dbHelper.close();
		}
	}
	
	private void viewCalendar() {
		Intent i = new Intent(this, CalendarView.class);
		startActivity(i);
	}
	
	private void viewEvents() {
		Intent i = new Intent(this, events.class);
		startActivity(i);
	}
	
	private void viewClass() {
		Intent i = new Intent(this, univ_classes.class);
		startActivity(i);
	}
	
	private void elearningSync() {
		Intent i = new Intent(this, ElearningPortal.class);
		startActivity(i);
	}
	
	private void viewEventType() {
		Intent i = new Intent(this, event_types.class);
		startActivity(i);
	}	
	
//	private void viewPriority() {
//		Intent i = new Intent(this, priorities.class);
//		startActivity(i);
//	}
	
	private void viewPreferences() {
		Intent i = new Intent(this, AskUserPass.class);
		startActivity(i);
	}
	
    private void setLastSyncText() {
    	String last_sync = "";
    	String status = "";
        TextView txtSync = (TextView) this.findViewById(R.id.txtEventsSyncTime);
        TextView txtStatus = (TextView) this.findViewById(R.id.txtEventsSyncSuccess);
        
    	try {
    		Cursor result;
			
			result = dbHelper.getElearnLog();
						
			startManagingCursor(result);

			if(result.getCount() > 0)
			{
				result.moveToFirst();
				last_sync = result.getString(result.getColumnIndexOrThrow(CalDbAdapter.ELEARN_LOG_DATE));
				status = result.getString(result.getColumnIndexOrThrow(CalDbAdapter.ELEARN_LOG_STATUS));
				
				txtSync.setText("  " + last_sync);
		        txtStatus.setText("  " + status);
			}
			
			result.close();
    	} catch(Exception e) {
    		txtSync.setText(last_sync);
	        txtStatus.setText(status);
    	}
    }  	
}